package com.leyou.auth.web;

import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.pojo.UserInfo;
import com.leyou.auth.service.AuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.util.CookieUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@EnableConfigurationProperties(JwtProperties.class)
public class AuthController {

    @Autowired
    private AuthService authService;

    @Value("${ly.jwt.cookieName}")
    private String cookieName;

    @Autowired
    private  JwtProperties prop;

    @PostMapping("/login")
    public ResponseEntity<Void> login(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            HttpServletResponse response,
            HttpServletRequest request
    ){
        //登录
        String token = authService.login(username,password);
        //写入Cookie
        CookieUtils.newBuilder(response).httpOnly().request(request)
                .build(cookieName,token);
        return  ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    /**
     * 通过请求传入的cookie 来解析对于的username
     * @param token
     * @return
     */
    @GetMapping("/verify")
    public ResponseEntity<UserInfo> verify(@CookieValue("LY_TOKEN") String token,
                                           HttpServletResponse response,
                                           HttpServletRequest request){
            if(StringUtils.isBlank(token)){
                //没有token
                throw  new LyException(ExceptionEnum.UNAUTHORIZED);
            }
            try {
                //解析token
                UserInfo userInfo = JwtUtils.getUserInfo(prop.getPublicKey(), token);
                //刷新token  每次活动一次用户信息 表示用户一直在活跃者，不能让这样的用户在30分钟后再次登录。
                String newToken = JwtUtils.generateToken(userInfo, prop.getPrivateKey(), prop.getExpire());
                //重写写入Cookie
                CookieUtils.newBuilder(response).httpOnly().request(request)
                        .build(cookieName,token);
                //返回登录用户信息
                return ResponseEntity.ok(userInfo);
            }catch (Exception e){
                //token 过期 或者被token被修改
                throw  new LyException(ExceptionEnum.UNAUTHORIZED);
            }
    }
}
